package com.two.screen.water.balance.utils

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.hardware.input.InputManager
import android.hardware.usb.UsbDevice
import android.hardware.usb.UsbDeviceConnection
import android.hardware.usb.UsbManager
import android.os.Parcelable
import android.os.SystemClock
import android.view.InputDevice
import android.view.KeyCharacterMap
import android.view.KeyEvent
import com.two.screen.water.balance.ui.App


object UsbKey {
    private var usbManager: UsbManager? = null
    private var inputManager: InputManager? = null


    // 注册一个广播接收器来监听USB设备的连接
    var connection: UsbDeviceConnection? = null
    var usbDevice: UsbDevice? = null
    fun init() {
        usbManager = App.context!!.getSystemService(Context.USB_SERVICE) as UsbManager
        inputManager = App.context!!.getSystemService(Context.INPUT_SERVICE) as InputManager

        // 注册广播
        val filter = IntentFilter()
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED)
        App.context!!.registerReceiver(usbReceiver, filter)
    }


    var usbReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action
            if (UsbManager.ACTION_USB_DEVICE_ATTACHED == action) {
                usbDevice = intent.getParcelableExtra<Parcelable>(UsbManager.EXTRA_DEVICE) as UsbDevice?
                if (usbManager!!.hasPermission(usbDevice)) {
                    // 获取设备连接
                    connection = usbManager!!.openDevice(usbDevice)
                    // 这里可以处理连接后的操作
                    // ...
                }
            }
        }
    }

    // 处理按键事件的方法
    private fun dispatchKeyEvent(keyCode: Int, metaState: Int) {
        val eventTime = SystemClock.uptimeMillis()
        val keyEvent = KeyEvent(
            eventTime, eventTime,
            KeyEvent.ACTION_DOWN, keyCode, 0, metaState,
            KeyCharacterMap.VIRTUAL_KEYBOARD, 0, 0, InputDevice.SOURCE_KEYBOARD
        )
//        inputManager?.verifyInputEvent(keyEvent)
//        inputManager?.injectInputEvent(keyEvent)
    }

    fun close() {
        // 当不需要监听时，注销广播和释放资源
        App.context!!.unregisterReceiver(usbReceiver)
        connection?.close()
    }
}